function formatPenaltyIndex(stat, index, kind) {
    if (!kind) kind = "major";
    var penalties = stat[kind + "Penalties"];
    if (!penalties)
        return "-";
    if (index >= penalties.length) {
        return "-";
    }
    var penalty = penalties[index];
    var desc = DXML.penaltyCodes[penalty.penalty];
    if (!desc) {
        desc = "Unknown Penalty (" + penalty.penalty + ")";
    }
    var code = penalty.penalty;
    if (penalty.position == "jammer") {
        code = code + "<div>" + DXML.jamJammerMarker + "</div>";
    } else if (penalty.position == "pivot") {
        code = code + "<div>" + DXML.jamPivotMarker + "</div>";
    }
    return '<div class="penalty ' + kind + '"><div class="hoverpenalty">' + desc + " P:" + (index+1) + " J:" + penalty.jam + '</div>' + code + "</div>";
}
function rosterStats(stats,position, team) {
    // finally, return a value for these things
    var retval = [];
    $(team).find('person').each(function (index, person) {
        var name = $(person).attr("name");
        var number = $(person).attr("number");
        var stat = stats[number][position];
        if (stats[number]["blocker_pivot_jammer"].jamCount == 0)
            return; // don't list somebody who didn't skate
        stat.skname = name || number;
        stat.number = number;
        stat.totalJams = stats[number]["blocker_pivot_jammer"].jamCount
        retval.push(stat);
    });
    return retval;
}

function sumAE(stat, list) {
    var total = 0;
    $(list).each(function (index, field) {
        if (stat.actionsErrors[field]) {
            total += stat.actionsErrors[field];
        }
    });
    if (total) {
        return threeDigits(total);
    }
    return "-";
}
DXML.skatersColumns = [
// common
        { title: "Player", data: "skname",class:"minsep", width:118, topHeader:"", topHeaderSpan:3 },
        { title: "Total</br>Jams", width:30, data: "totalJams"},
        { class: "majsep", width:10, orderable: false, data: null, defaultContent:"" },
// points        
        { title: "#<br/>Jams", data: "jamCount", name:"points", topHeader:"Any Position", topHeaderSpan:11, topHeaderClass:"majorheading skaterPositionFilterHeader"},
        { title: "#<br/>Lead", data: "lead", name:"points" },
        { title: "%<br/>Lead", data: function(stat) {return percent(stat.lead, stat.jamCount);}, width:54, name:"points", footer:"lead" },
        { title: "%<br/>Lost", data: function(stat) {return percent(stat.lost, stat.jamCount);}, width:54, name:"points", footer:"lost" },
        { title: "%<br/>Called", data: function(stat) {return percent(stat.call, stat.jamCount);}, width:54, name:"points", footer:"call" },
        { title: "%<br/>NP", data: function(stat) {return percent(stat.noPass, stat.jamCount);}, width:54, name:"points", footer:"noPass" },
        { title: "+", data: function(stat) {return stat.jamCount ? threeDigits(stat.points) : "-";}, name:"points", footer:"points" },
        { title: "-", data: function(stat) {return stat.jamCount ? ColorTD(-stat.oppPoints) : "-";}, type:"html-num", name:"points", footer:"oppPoints" },
        { title: "Total<br/>+/-", data: function(stat) {return stat.jamCount ?ColorTD(stat.points - stat.oppPoints) : "-";}, type:"html-num", name:"points", footer:"points" },
        { title: "AVG<br/>+/-", data: function(stat) {return stat.jamCount ? ColorTD((stat.points - stat.oppPoints) / stat.jamCount, true) : "-";}, type:"html-num", name:"points", footer:"points" },
        { title: "VTAR<br/>+/-", data: function(stat) {return stat.jamCount ? ColorTD((stat.points - stat.oppPoints) / stat.jamCount - stat.teamPosvtar, true) : "-";}, type:"html-num", name:"points" },
        { class: "majsep", width:10, orderable: false, data: null, defaultContent:"", name:"points", topHeader:"" },
        { title: "%<br/>Lost", data: function(stat) { return percent(stat.oppLost, stat.jamCount);}, width:54, name:"points",topHeader:"Opp. Jammer", topHeaderSpan:3, topHeaderClass:"majorheading" },
        { title: "%<br/>Called", data: function(stat) { return percent(stat.oppCall, stat.jamCount);}, width:54, name:"points" },
        { title: "%<br/>NP", data: function(stat) { return percent(stat.oppNoPass, stat.jamCount);}, width:54, name:"points" },
        { class: "majsep", width:10, orderable: false, data: null, defaultContent:"", name:"points", topHeader:"" },
//        { title: "Maj.", data: "asPos" , name:"points"},
        { title: "Maj.", data: "majors", name:"points", topHeader:"" },
        { title: "Exp.", data: "explusions", name:"points", topHeader:"" },
        // penalties
        { title: "1",width:48,type:"html", name:"penalties",data: function(stat) { return formatPenaltyIndex(stat, 0);}, visible:false, topHeader:"Majors", topHeaderClass:"majorheading", topHeaderSpan:7},
        { title: "2",width:48,type:"html", name:"penalties",data: function(stat) { return formatPenaltyIndex(stat, 1);}, visible:false },
        { title: "3",width:48,type:"html", name:"penalties",data: function(stat) { return formatPenaltyIndex(stat, 2);}, visible:false },
        { title: "4",width:48,type:"html", name:"penalties",data: function(stat) { return formatPenaltyIndex(stat, 3);}, visible:false },
        { title: "5",width:48,type:"html", name:"penalties",data: function(stat) { return formatPenaltyIndex(stat, 4);}, visible:false },
        { title: "6",width:48,type:"html", name:"penalties",data: function(stat) { return formatPenaltyIndex(stat, 5);}, visible:false },
        { title: "7",width:48,type:"html", name:"penalties",data: function(stat) { return formatPenaltyIndex(stat, 6);}, visible:false },
        { class: "majsep", width:10, orderable: false, data: null, defaultContent:"", name:"penalties", visible:false, topHeader:"" },
        { title: "Exp",width:48,type:"html", name:"penalties",data: function(stat) { return formatPenaltyIndex(stat, 0,"expulsion");}, visible:false, topHeader:"" },
        // actions
        { title: "Offensive<br/>Blocks", class:"asjammer", name:"actions", data: function (stat) {
            return threeDigits(stat.actionsErrors["Offensive Block"]);}, defaultContent:"", visible:false, topHeader:"Offensive Assists", topHeaderClass:"majorheading", topHeaderSpan:6 },
        { title: "Offensive<br/>Knockdowns", class:"asjammer", name:"actions",data: function (stat) {
            return threeDigits(stat.actionsErrors["Offensive Knockdown"]);}, defaultContent:"", visible:false },
        { title: "Whips", class:"asjammer", name:"actions",data: function (stat) {
            return threeDigits(stat.actionsErrors["Whip"]);}, defaultContent:"", visible:false },
        { title: "Pushes", class:"asjammer", name:"actions",data: function (stat) {
            return threeDigits(stat.actionsErrors["Push"]);}, defaultContent:"", visible:false },
        { title: "Bulldozes", class:"asjammer minsep", name:"actions",data: function (stat) {
            return threeDigits(stat.actionsErrors["Bulldozer"]);}, defaultContent:"", visible:false },
        { title: "Total<br/>Off", class:"asjammer", name:"actions",data: function (stat) {
            return sumAE(stat,["Offensive Block","Offensive Knockdown","Whip","Push","Bulldozer"]);}, defaultContent:"", visible:false },
        { class: "majsep", width:10, orderable: false, data: null, defaultContent:"", name:"actions", visible:false, topHeader:"" },
        { title: "1/4<br/>Track", class:"asblocker", name:"actions",data: function (stat) {
            return threeDigits(stat.actionsErrors["1/4 Track Jammer Block"]);}, defaultContent:"", visible:false, topHeader:"Defensive Assists", topHeaderClass:"majorheading", topHeaderSpan:6 },
        { title: "Jammer<br/>Forceouts", class:"asblocker", name:"actions",data: function (stat) {
            return threeDigits(stat.actionsErrors["Jammer Force Out"]);}, defaultContent:"", visible:false },
        { title: "Hits on<br/>Jammer", class:"asblocker", name:"actions",data: function (stat) {
            return threeDigits(stat.actionsErrors["Hit On Jammer"]);}, defaultContent:"", visible:false },
        { title: "Jammer<br/>Knockdown", class:"asblocker", name:"actions",data: function (stat) {
            return threeDigits(stat.actionsErrors["Jammer Knockdown"]);}, defaultContent:"", visible:false },
        { title: "Block<br/>Assists", class:"asblocker minsep", name:"actions",data: function (stat) {
            return threeDigits(stat.actionsErrors["Block Assist"]);}, defaultContent:"", visible:false },
        { title: "Total<br/>Def", class:"asblocker", name:"actions",data: function (stat) {
            return sumAE(stat,["1/4 Track Jammer Block","Jammer Force Out","Hit On Jammer","Jammer Knockdown","Block Assist"]);}, defaultContent:"", visible:false },
        // errors
        { title: "Off Blk<br/>Assist", class:"asjammer", name:"errors",data: function (stat) {
            return threeDigits(stat.actionsErrors["Offensive Block Assist"]);}, defaultContent:"", visible:false, topHeader:"Jammer Actions", topHeaderClass:"majorheading", topHeaderSpan:6 },
        { title: "<br/>Juke", class:"asjammer", name:"errors",data: function (stat) {
            return threeDigits(stat.actionsErrors["Juke"]);}, defaultContent:"", visible:false },
        { title: "<br/>Jump", class:"asjammer", name:"errors",data: function (stat) {
            return threeDigits(stat.actionsErrors["Jump"]);}, defaultContent:"", visible:false },
        { title: "<br/>Rolloff", class:"asjammer", name:"errors",data: function (stat) {
            return threeDigits(stat.actionsErrors["Rolloff"]);}, defaultContent:"", visible:false },
        { title: "Hip<br/>Whip", class:"asjammer", name:"errors",data: function (stat) {
            return threeDigits(stat.actionsErrors["Hip Whip"]);}, defaultContent:"", visible:false },
        { title: "Total<br/>Assts", class:"asjammer", name:"errors",data: function (stat) {
            return sumAE(stat,["Offensive Block Assist","Juke","Jump","Rolloff","Hip Whip"]);}, defaultContent:"", visible:false },
        { class: "majsep", width:10, orderable: false, data: null, defaultContent:"", name:"errors", visible:false, topHeader:"" },
        { title: "<br/>Juked", class:"asblocker", name:"errors",data: function (stat) {
            return threeDigits(stat.actionsErrors["Juked"]);}, defaultContent:"", visible:false, topHeader:"Errors", topHeaderClass:"majorheading", topHeaderSpan:6 },
        { title: "Missed<br/>Hit", class:"asblocker", name:"errors",data: function (stat) {
            return threeDigits(stat.actionsErrors["Missed Hit"]);}, defaultContent:"", visible:false },
        { title: "Ineffective<br/>Hit", class:"asblocker", name:"errors",data: function (stat) {
            return threeDigits(stat.actionsErrors["Ineffective Hit"]);}, defaultContent:"", visible:false },
        { title: "Hit &amp;<br/>Fall", class:"asblocker", name:"errors",data: function (stat) {
            return threeDigits(stat.actionsErrors["Hit And Fall"]);}, defaultContent:"", visible:false },
        { title: "Knocked<br/>Down", class:"asblocker minsep", name:"errors",data: function (stat) {
            return threeDigits(stat.actionsErrors["Knocked Down"]);}, defaultContent:"", visible:false },
        { title: "Total<br/>Errs", class:"asblocker", name:"errors",data: function (stat) { return sumAE(stat,["Juked","Missed Hit","Ineffective Hit","Hit And Fall","Knocked Down"]);}, defaultContent:"", visible:false },
    ];

function topHeaderForSkatersTable(filter) {
    var str = "";
    $(DXML.skatersColumns).each(function (index, value) {
        if (value.name == filter || value.name == undefined) {
            if (value.topHeader != undefined) {
                str += "<th";
                if (value.topHeaderSpan) {
                    str += " colspan=\""+value.topHeaderSpan+"\"";
                }
                if (value.topHeaderClass) {
                    str += " class=\""+value.topHeaderClass+"\"";
                }
                str += ">" + value.topHeader + "</th>";
            }
        }
    });
    str += "";
    return str;
}

function footerForSkaterTable(tfoot, data, start, end, display) {
    var api = this.api();
    var columnsShown = api.columns()[0];
    var footer = "";
    var totals = {};
    $(columnsShown).each(function (index, colNum) {
        var colInfo = DXML.skatersColumns[colNum];
        var dataSrc = colInfo.data;
        var field = null;
        if (colInfo.data === null) {
        } else if (dataSrc.constructor === String) {
            field = dataSrc;
        } else if (colNum == 0) {
        } else {
            field = colInfo.footer;
        }
        if (field) {
            var total = 0;
            var count = 0;
            $(api.data()).each( function (index, value) {
                total += value[field];
                count += 1;
            });
            if (count) {
                totals[field] = total / count;
            }
        }
    });
    $(columnsShown).each(function (index, colNum) {
        footer += "<td>";
        var colInfo = DXML.skatersColumns[colNum];
        var dataSrc = colInfo.data;
        if (colNum == 0) {
            footer += "Average";
        } else if (colInfo.data === null) {
        } else if (dataSrc.constructor === String) {
            footer += ColorTD(data[dataSrc]);
        } else {
            footer += dataSrc(totals);
        }
        footer += "</td>";
    });
    $(tfoot).html( footer);
}


function prepareSkatersPage() {
    if (!DXML.firstPeriod) {
        return;
    }
    $("#skatersPageFilter #Errors").button( "option", "disabled", $([DXML.firstPeriod, DXML.secondPeriod]).find("error").length == 0);
    $("#skatersPageFilter #Actions").button( "option", "disabled", $([DXML.firstPeriod, DXML.secondPeriod]).find("action").length == 0);
    DXML.stats = buildStats(DXML.homeTeam, DXML.awayTeam, DXML.firstPeriod, DXML.secondPeriod);
    function statHeader(team, side, other) {
        return {
            name:extractName(team, other) || side.toUpperCase(),
            side:side
        };
    }
    Tempo.prepare($('#skatersPage')).render([
        statHeader(DXML.homeTeam, "home", DXML.awayTeam),
        statHeader(DXML.awayTeam, "away", DXML.homeTeam)
    ]);
    $(".skatersMetaHeader").html(topHeaderForSkatersTable("points"));
    var homeStats = rosterStats(DXML.stats.home,"blocker_pivot_jammer", DXML.homeTeam);
    var awayStats = rosterStats(DXML.stats.away,"blocker_pivot_jammer", DXML.awayTeam);
    
//    var headerCallback = function( thead, data, start, end, display ) {
//        if ($(thead.parentElement).find("tr").length == 1) {
//            $(thead.parentElement).prepend($("<th>"+topHeaderForSkatersTable("points")+"</th>"));
//        }
//    };
    var columns = DXML.skatersColumns;
    var tableH = $("#homeSkaters").DataTable({
        paging: false,
        searching: false,
        info: false,
        data: homeStats,
        columns: columns,
//        footerCallback: footerForSkaterTable
    });
//    new $.fn.dataTable.FixedHeader( tableH );
    var tableA = $("#awaySkaters").DataTable({
        paging: false,
        searching: false,
        info: false,
        data: awayStats,
        columns: columns,
//        footerCallback: footerForSkaterTable
    });
//    new $.fn.dataTable.FixedHeader( tableA );
}

function uidFromSkaterNameOrNumber(nameOrNumber) {
    return nameOrNumber.replace(/[^\w]/gi, '');
}

function divForSkater(skaterName, skaterNumber, prefix,postfix) {
    if (!prefix) prefix = "";
    if (!postfix) postfix = "";
    var nameAndNumber;
    var nameOrNumber;
    if (skaterName && skaterNumber) {
        nameAndNumber = skaterName + " (" + skaterNumber + ")";
        nameOrNumber = skaterName;
    } else if (skaterName) {
        nameAndNumber = skaterName;
        nameOrNumber = skaterName;
    } else if (skaterNumber) {
        nameAndNumber = skaterNumber;
        nameOrNumber = skaterNumber;
    } else {
        nameAndNumber = "???";
        nameOrNumber = "???";
    }
    return '<div class="player" title="' + nameAndNumber + '" uid="'+uidFromSkaterNameOrNumber(nameOrNumber)+'">' + prefix + '<span style="position:relative; top:-3px;">' + nameOrNumber + "</span>" + postfix + '</div>';
}

function filterSkatersPage(value) {
    function refilter(filter, title) {
        if ($(".skaterPositionFilterHeader").first().text() == title)
            return; // already good
        $(".skaterPositionFilterHeader").text(title);
        tableH.clear();
        $(rosterStats(DXML.stats.home,filter, DXML.homeTeam)).each(function (index, value) {
            tableH.row.add(value);
        });
        tableA.clear();
        $(rosterStats(DXML.stats.away,filter, DXML.awayTeam)).each(function (index, value) {
            tableA.row.add(value);
        });
//        tableA.DataTable().rows().invalidate().draw();
//        tableH.DataTable().rows().invalidate().draw();
        tableA.draw();
        tableH.draw();
    }
    function showColumns(name) {
        $(".skatersMetaHeader").html(topHeaderForSkatersTable(name));
        $(["points","penalties","actions","errors"]).each(function (index, value) {
            tableH.columns(value +":name").visible(false);
            tableA.columns(value +":name").visible(false);
        });
        $(["points","penalties","actions","errors"]).each(function (index, value) {
            if (value == name) {
                tableH.columns(value +":name").visible(true);
                tableA.columns(value +":name").visible(true);
            }
        });
        $(".skatersMetaHeader").html(topHeaderForSkatersTable(name));
//        $("#homeSkaters thead").first().html(topHeaderForSkatersTable(name));
//        $("#awaySkaters thead").first().html(topHeaderForSkatersTable(name));
    }
    var tableH = $("#homeSkaters").DataTable();
    var tableA = $("#awaySkaters").DataTable();
    if (value == 'AnyPosition') {
        showColumns("points");
        refilter("blocker_pivot_jammer", "Any Position");
    } else if (value == "AsJammer") {
        showColumns("points");
        refilter("jammer", "As Jammer");
    } else if (value == "AsBlocker") {
        showColumns("points");
        refilter("blocker_pivot", "As Pivot/Blocker");
    } else if (value == "Penalties") {
        showColumns("penalties");
        refilter("blocker_pivot_jammer", "Any Position");
    } else if (value == "Actions") {
        showColumns("actions");
        refilter("blocker_pivot_jammer", "Any Position");
    } else if (value == "Errors") {
        showColumns("errors");
        refilter("blocker_pivot_jammer", "Any Position");
    }
    
}

